package com.cman777.springc.ratelimiter.alg.storage;

import lombok.AllArgsConstructor;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author chenzhicong
 * @time 2020/10/26 13:35
 */
@AllArgsConstructor
public class RedissonStorageAdapter implements RedisStorage {
    private RedissonClient redissonClient;

    @Override
    public Long incrementAndGet(String key) {
        return redissonClient.getAtomicLong(key).incrementAndGet();
    }

    @Override
    public boolean setIfAbsent(String key, Long value, Long time, TimeUnit timeUnit) {
        RAtomicLong rAtomicLong = redissonClient.getAtomicLong(key);
        if (rAtomicLong.compareAndSet(0, value)) {
            rAtomicLong.expire(time, timeUnit);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean expire(String key, long unit, TimeUnit timeUnit) {
        RAtomicLong rAtomicLong = redissonClient.getAtomicLong(key);
        return rAtomicLong.expire(unit, timeUnit);
    }
}
